// 管理员路由
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const Association = require('../models/Association');
const AssociationMember = require('../models/AssociationMember');
const Tip = require('../models/Tip');
const Message = require('../models/Message');
const EmergencyPhone = require('../models/EmergencyPhone');
const { Op } = require('sequelize');

/**
 * 管理员登录
 * @route POST /api/admin/login
 * @description 管理员登录接口
 * @access Public
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 这里应该有管理员账号验证逻辑
    // 实际应用中应该从数据库中查询管理员信息并验证密码
    
    // 临时处理，仅用于演示
    if (username === 'admin' && password === 'admin123') {
      res.status(200).json({
        success: true,
        token: 'admin_token', // 实际应用中应该生成真实的token
        message: '登录成功'
      });
    } else {
      res.status(401).json({ message: '用户名或密码错误' });
    }
  } catch (error) {
    console.error('管理员登录失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取用户列表
 * @route GET /api/admin/users
 * @description 获取用户列表，支持分页和搜索
 * @access Private (Admin)
 */
router.get('/users', async (req, res) => {
  try {
    const { page = 1, size = 20, keyword = '', status = '' } = req.query;
    const offset = (page - 1) * size;
    
    const whereCondition = {};
    
    // 关键词搜索
    if (keyword) {
      whereCondition[Op.or] = [
        { nickName: { [Op.like]: `%${keyword}%` } },
        { phone: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    // 状态筛选
    if (status !== '') {
      whereCondition.status = parseInt(status);
    }
    
    const { count, rows } = await User.findAndCountAll({
      where: whereCondition,
      limit: parseInt(size),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
    
    res.status(200).json({
      success: true,
      data: rows,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / size)
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 审核社团
 * @route PUT /api/admin/associations/:id/audit
 * @description 审核社团申请
 * @access Private (Admin)
 */
router.put('/associations/:id/audit', async (req, res) => {
  try {
    const { id } = req.params;
    const { status, reason } = req.body;
    
    // 查询社团
    const association = await Association.findByPk(id);
    
    if (!association) {
      return res.status(404).json({ message: '社团不存在' });
    }
    
    // 更新社团状态
    await association.update({ status: parseInt(status) });
    
    res.status(200).json({
      success: true,
      message: status === 1 ? '社团审核通过' : '社团审核未通过',
      data: association
    });
  } catch (error) {
    console.error('审核社团失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 审核贴士
 * @route PUT /api/admin/tips/:id/audit
 * @description 审核留学贴士
 * @access Private (Admin)
 */
router.put('/tips/:id/audit', async (req, res) => {
  try {
    const { id } = req.params;
    const { status, reason } = req.body;
    
    // 查询贴士
    const tip = await Tip.findByPk(id);
    
    if (!tip) {
      return res.status(404).json({ message: '贴士不存在' });
    }
    
    // 更新贴士状态
    await tip.update({ status: parseInt(status) });
    
    res.status(200).json({
      success: true,
      message: status === 1 ? '贴士审核通过' : '贴士审核未通过',
      data: tip
    });
  } catch (error) {
    console.error('审核贴士失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取留言列表
 * @route GET /api/admin/messages
 * @description 获取所有用户留言
 * @access Private (Admin)
 */
router.get('/messages', async (req, res) => {
  try {
    const { page = 1, size = 20, type = '', isRead = '' } = req.query;
    const offset = (page - 1) * size;
    
    const whereCondition = {};
    
    // 类型筛选
    if (type) {
      whereCondition.type = type;
    }
    
    // 是否已读筛选
    if (isRead !== '') {
      whereCondition.isRead = isRead === 'true';
    }
    
    const { count, rows } = await Message.findAndCountAll({
      where: whereCondition,
      limit: parseInt(size),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
    
    res.status(200).json({
      success: true,
      data: rows,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / size)
    });
  } catch (error) {
    console.error('获取留言列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 管理应急电话
 * @route POST /api/admin/emergency-phones
 * @description 添加应急电话
 * @access Private (Admin)
 */
router.post('/emergency-phones', async (req, res) => {
  try {
    const { name, phoneNumber, category, country, description, isCommon, order } = req.body;
    
    // 验证必填字段
    if (!name || !phoneNumber || !category) {
      return res.status(400).json({ message: '缺少必要的电话信息' });
    }
    
    // 创建应急电话
    const phone = await EmergencyPhone.create({
      name,
      phoneNumber,
      category,
      country,
      description,
      isCommon: isCommon || false,
      order: order || 0
    });
    
    res.status(201).json({ success: true, data: phone, message: '应急电话添加成功' });
  } catch (error) {
    console.error('添加应急电话失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;